package com.example.springbootmybatisplus.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.example.springbootmybatisplus.bean.User;
import com.example.springbootmybatisplus.bean.UserVo;
import com.example.springbootmybatisplus.commonutils.BusinessException;
import com.example.springbootmybatisplus.commonutils.R;
import com.example.springbootmybatisplus.config.AppProperties;
import com.example.springbootmybatisplus.service.UserInfoService;
import com.example.springbootmybatisplus.utils.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lfh
 * @since 2022-11-19
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {


    // private final UserService UserService;
    //
    private final UserInfoService service;


    private  AppProperties appProperties;

    // @PostMapping("/insertUser2")
    // public R insertUser2(@RequestBody User user){
    //     return UserService.save(user) ? R.ok("新增成功!"):R.error("新增失败!");
    // }
    // /**
    //  * 根据ID查询用户信息
    //  * @param id
    //  * @return
    //  */
    // @GetMapping("/getOneUser/{id}")
    // @SensitiveAnnotation(field = {"name","phone"})
    // public User getOneUser(@PathVariable("id") Integer id){
    //     return UserService.getById(id);
    // }
    //
    /**
     * 获取所有的用户信息
     * @return
     */
    // @GetMapping("/getAllUser")
    // @SensitiveAnnotation(field = {"name","phone"})
    // public List<User> getAllUser(){
    //     return UserService.list();
    // }
    /**
     * 获取符合条件的用户
     *
     * @return
     */
    @PostMapping("/getUser")
    public List<UserVo> getAllUser(@Validated @RequestBody User user){
        Page<User> page = Db.lambdaQuery(User.class)
                .eq(Objects.nonNull(user.getId()), User::getId, user.getId())
                .like(StringUtils.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .like(StringUtils.isNotBlank(user.getName()), User::getName, user.getName()).page(new Page<>(2,5));
        return JSON.parseArray(JSON.toJSONString(page.getRecords()), UserVo.class);
    }

    @PostMapping("/getUser2")
    public List<UserVo> getAllUser2(@Validated @RequestBody User user){
        Page<User> page = Db.lambdaQuery(User.class)
                .eq(Objects.nonNull(user.getId()), User::getId, user.getId())
                .like(StringUtils.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .like(StringUtils.isNotBlank(user.getName()), User::getName, user.getName()).page(new Page<>(2,5));
        return JSON.parseArray(JSON.toJSONString(page.getRecords()), UserVo.class).stream().map(item-> BeanUtil.convert(item, UserVo.class)).collect(Collectors.toList());
    }
    @PostMapping("/getUser3")
    public List<UserVo> getAllUser3(@Validated @RequestBody User user){
        // boolean b = SqlHelper.retBool();判断插入大于0
        Page<User> page = Db.lambdaQuery(User.class)
                .eq(Objects.nonNull(user.getId()), User::getId, user.getId())
                .like(StringUtils.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .like(StringUtils.isNotBlank(user.getName()), User::getName, user.getName()).page(new Page<>(2,5));
        log.error("page:[{}]","page");
        return   Optional.ofNullable(page.getRecords()).map(item-> BeanUtil.convert(item, UserVo.class)).orElse(Collections.emptyList());
    }
    //获取系统配置

    @PostMapping("/getConfig")
    public AppProperties getConfig(){
        // AppProperties appProperties1 = appProperties;
        // System.out.println(appProperties.getName());
        Integer i = null;
        System.out.println(i);
        String aa = "Fdf";
        StringBuffer stringBuffer = new StringBuffer();
        return appProperties;
    }

    //
    // @PostMapping("/getUser2")
    // public List<UserVo> getAllUser2(@RequestBody User user){
    //     // //先把异常校验写前面
    //     // if (StringUtils.isBlank(user.getName())) {
    //     //     throw new RuntimeException("名字不为空!");
    //     // }
    //     // LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    //     // wrapper.eq(Objects.nonNull(user.getId()),User::getId,user.getId());
    //     // wrapper.like(StringUtils.isNotBlank(user.getName()),User::getName,user.getName());
    //     // List<User> list = UserService.list(wrapper);
    //     // if(CollectionUtil.isEmpty(list)){
    //     //     return Collections.EMPTY_LIST;
    //     // }
    //     // return BeanUtil.copyToList(list, UserVo.class);
    //     return null;
    // }
    //
    @PostMapping("/insertUser")
    public R insertUser(@RequestBody @Valid User user){
        // user.builder().age().build()
        try {
            if(Db.save(user)){
                throw new BusinessException(500,"新增失败");
            }
        } catch (Exception e) {
            if(e instanceof BusinessException){
                log.error("{},请求参数param：{}", ((BusinessException) e).getMsg(), JSON.toJSONString(user));
            }else {
                log.error("[{}]新增失败，请求参数：{}",user.getName(),JSON.toJSONString(user),e);
            }
            throw e;
        }
        return R.ok();
    }
    //
    // @PutMapping("/updatetUser")
    // public R updatetUser(@RequestBody @Validated UserInfo user){
    //     return service.updateById(user) ? R.ok("修改成功!"):R.error("修改失败!");
    // }
    //
    // /**
    //  * 优化for循环
    //  * @param user
    //  * @return
    //  */
    // @PostMapping("/getUser2")
    // public List<UserVo> getYH(@RequestBody User user){
    //     // //先把异常校验写前面
    //     // if (StringUtils.isBlank(user.getName())) {
    //     //     throw new RuntimeException("名字不为空!");
    //     // }
    //     // LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    //     // wrapper.eq(Objects.nonNull(user.getId()),User::getId,user.getId());
    //     // wrapper.like(StringUtils.isNotBlank(user.getName()),User::getName,user.getName());
    //     // List<User> list = UserService.list(wrapper);
    //     // if(CollectionUtil.isEmpty(list)){
    //     //     return Collections.EMPTY_LIST;
    //     // }
    //     // Str
    //     // return BeanUtil.copyToList(list, UserVo.class);
    //     List<User> list = Db.lambdaQuery(User.class).list();
    //     Map<Long, List<User>> collect = list.stream().parallel().collect(Collectors.groupingBy(User::getId));
    //     Map<String, List<User>> collected = list.stream().parallel().collect(Collectors.groupingBy(User::getName));
    //     list.stream().parallel().forEach(item ->{
    //         item.setId(collected.get(item.getName()).get(0).getId());
    //     });
    //     return null;
    // }


}
